#!/usr/bin/python
# Copyright 2011 Alex K (wtwf.com) All rights reserved.

"""fetchlog: loads Power, Daily yield and Total yield from a SMA Sunny
Webbox homepage.
"""

import sys
import urllib
import datetime
import csv
import time

def GetSolarProduction():
  o = urllib.urlopen('http://10.1.10.27/home.htm')

  want = ('id="Power"', 'id="DailyYield"', 'id="TotalYield"')
  ans = [0, 0, 0]
  count = 0
  for line in o:
    for x in want:
      if x in line:
        ans[count] = line[line.find('>') + 1:
                          line.rfind(' ', 0, line.rfind('<'))].strip()
        count += 1
        break
    if count == len(want):
      break
  o.close()
  return ans

def WriteLogLine(ans):
  filename = "/Users/ark/solarlog.%s.csv" % datetime.date.today().isoformat()
  out = open(filename, "a")
  line = ",".join([datetime.datetime.utcnow().isoformat(),
                   datetime.datetime.now().isoformat()] + ans)
  out.write(line + "\n")
  print line
  out.close()


def Main(args):
  while True:
    try:
      WriteLogLine(GetSolarProduction())
    except:
      pass
    stime = 60 - datetime.datetime.now().second
    if stime < 1:
      stime = 60
    time.sleep(stime)

if __name__ == '__main__':
  Main(sys.argv)
